package com.cavasmonitor;

import java.util.ArrayList;
import java.util.List;

import com.cavasmonitor.db.CavasDao;
import com.cavasmonitor.to.AlarmaTo;
import com.cavasmonitor.to.EquipoTo;
import com.cavasmonitor.to.UsuarioTo;
import com.cavasmonitor.util.Session;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

public class AlarmasActivity extends Activity {

	Spinner s;
	Long id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.alarmas);

		ImageButton img = (ImageButton) findViewById(R.id.btnHome);

		img.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent i = new Intent(AlarmasActivity.this,
						OpcionesActivity.class);
				startActivityForResult(i, 1);
			}
		});

		img = (ImageButton) findViewById(R.id.btnExit);

		img.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				new AlertDialog.Builder(AlarmasActivity.this)
						.setTitle(R.string.msg_salir)
						.setMessage(R.string.msg_logout)
						.setPositiveButton(R.string.msg_aceptar,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										Session.usuario = null;
										Intent i = new Intent(
												AlarmasActivity.this,
												MainActivity.class);
										startActivityForResult(i, 1);
									}
								})
						.setNegativeButton(R.string.msg_cancelar, null).show();

			}
		});

		CavasDao dao = new CavasDao(AlarmasActivity.this);
		dao.open();

		List<EquipoTo> equipos = dao.getEquipos();
		List<String> list = new ArrayList<String>();

		list.add("-");
		if (equipos != null && !equipos.isEmpty())
			for (EquipoTo e : equipos) {
				list.add(e.getNombre() + " P:" + e.getPunto());
			}
		s = (Spinner) findViewById(R.id.spiEquipos);
		ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, list);
		spinnerArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(spinnerArrayAdapter);

		list = new ArrayList<String>();
		list.add("-");
		list.add("Advertencia");
		list.add("Critica");
		s = (Spinner) findViewById(R.id.spiTipoAlarma);
		spinnerArrayAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
		spinnerArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(spinnerArrayAdapter);

		List<AlarmaTo> alarmas = dao.getAlarmas();
		list = new ArrayList<String>();

		list.add("Seleccione la alarma a editar");
		if (alarmas != null && !alarmas.isEmpty())
			for (AlarmaTo a : alarmas) {
				list.add(a.getId() + "_" + a.getEquipo().getNombre());
			}
		s = (Spinner) findViewById(R.id.spiAlarmas);
		spinnerArrayAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
		spinnerArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(spinnerArrayAdapter);

		Button btn = (Button) findViewById(R.id.btnGuardar);

		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				String min = ((EditText) findViewById(R.id.inputVInf))
						.getText().toString().trim();
				String max = ((EditText) findViewById(R.id.inputVSup))
						.getText().toString().trim();

				Spinner spn = (Spinner) findViewById(R.id.spiTipoAlarma);
				Long tipo = spn.getSelectedItemId();

				spn = (Spinner) findViewById(R.id.spiEquipos);
				Long iequipo = spn.getSelectedItemId();

				if (tipo == 0) {
					new AlertDialog.Builder(AlarmasActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_alarma_tipo_req)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else if (iequipo == 0) {
					new AlertDialog.Builder(AlarmasActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_alarma_eq_req)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else if (max.length() == 0) {
					new AlertDialog.Builder(AlarmasActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_alarma_max_req)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else if (min.length() == 0) {
					new AlertDialog.Builder(AlarmasActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_alarma_min_req)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else if (Double.parseDouble(min) > Double.parseDouble(max)) {
					new AlertDialog.Builder(AlarmasActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_alarma_min_no_max)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else {

					CavasDao dao = new CavasDao(AlarmasActivity.this);
					dao.open();

					spn = (Spinner) findViewById(R.id.spiEquipos);
					Long punto = Long.valueOf(spn
							.getSelectedItem()
							.toString()
							.trim()
							.substring(
									spn.getSelectedItem().toString().trim()
											.lastIndexOf("P:") + 2));
					EquipoTo equipo = dao.getEquipoPorPunto(punto);

					AlarmaTo alarma;
					alarma = new AlarmaTo();
					alarma.setId(id);
					alarma.setEquipo(equipo);
					alarma.setTipo(AlarmaTo.Tipo.getTipo(tipo));
					alarma.setMin(Double.parseDouble(min));
					alarma.setMax(Double.parseDouble(max));

					if (id == 0)
						dao.createAlarma(alarma);
					else
						dao.updateAlarma(alarma);

					new AlertDialog.Builder(AlarmasActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_alarma_succ)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();					

					dao.close();
					
					Intent i = new Intent(AlarmasActivity.this,
							AlarmasActivity.class);
					startActivityForResult(i, 1);
				}
			}
		});

		s.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView,
					View selectedItemView, int position, long idx) {

				if (position > 0) {

					CavasDao dao = new CavasDao(AlarmasActivity.this);
					dao.open();

					Long co_id = Long.valueOf(s
							.getSelectedItem()
							.toString()
							.trim()
							.substring(
									0,
									s.getSelectedItem().toString().trim()
											.indexOf("_")));

					AlarmaTo alarma = dao.getAlarma(co_id);

					id = alarma.getId();

					EditText edt = (EditText) findViewById(R.id.inputVInf);
					edt.setText(alarma.getMin().toString());

					edt = (EditText) findViewById(R.id.inputVSup);
					edt.setText(alarma.getMax().toString());

					Spinner spn = (Spinner) findViewById(R.id.spiTipoAlarma);
					spn.setSelection(alarma.getTipo().getId().intValue());

					spn = (Spinner) findViewById(R.id.spiEquipos);

					int i = 0;
					for (i = 0; i < spn.getAdapter().getCount(); i++) {
						if (spn.getAdapter()
								.getItem(i)
								.toString()
								.equalsIgnoreCase(
										alarma.getEquipo().getNombre() + " P:"
												+ alarma.getEquipo().getPunto())) {
							break;
						}
					}
					spn.setSelection(i);

				} else {
					id = 0L;

					EditText edt = (EditText) findViewById(R.id.inputVInf);
					edt.setText("");

					edt = (EditText) findViewById(R.id.inputVSup);
					edt.setText("");

					Spinner spn = (Spinner) findViewById(R.id.spiTipoAlarma);
					spn.setSelection(0);

					spn = (Spinner) findViewById(R.id.spiEquipos);
					spn.setSelection(0);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {
				// your code here
			}
		});
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i;
		switch (item.getOrder()) {
		case Session.M_USUARIOS:
			i = new Intent(AlarmasActivity.this, UsuariosActivity.class);
			startActivityForResult(i, 1);
			return true;
		case Session.M_CFG:
			i = new Intent(AlarmasActivity.this, ConfiguracionActivity.class);
			startActivityForResult(i, 1);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		if (Session.usuario.getRol() == UsuarioTo.Rol.ADMINISTRADOR) {
			getMenuInflater().inflate(R.menu.main, menu);
		} 
		return true;
	}

}
